/**
 * @ClassName CoffeeMachine
 * @Description TODO
 * @Author Li
 * @Date 2022/8/9 16:10
 * @ModifyDate 2022/8/9 16:10
 * @Version 1.0
 */
public class CoffeeMachine extends Thread {
    private Coffee coffee;

    public CoffeeMachine(Coffee coffee) {
        this.coffee = coffee;
    }

    @Override
    public void run() {
        int count = 0;
        // 让咖啡机一致处于运行状态
        while (true) {
            synchronized (coffee) {
                /*
             如果咖啡已经存在，则让机器进入等待
             */
                if (coffee.state == true) {
                    try {
                        coffee.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("开始制作咖啡！");
            /*
             沉睡3秒，模拟制作咖啡时间
             */
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            /*
             没有咖啡，进入生产
             可以制作三种咖啡
             */
                if (count % 3 == 0) {
                    coffee.capacity = "小杯";
                    coffee.sugar = "低糖";
                } else if (count % 3 == 1) {
                    coffee.capacity = "大杯";
                    coffee.sugar = "低糖";
                } else if (count % 3 == 2) {
                    coffee.capacity = "大杯";
                    coffee.sugar = "高糖";
                }
                count++;
                coffee.state = true; // 标记咖啡已经做好了，存在
                System.out.println("已经制作好了：" + coffee.capacity + coffee.sugar + "咖啡！");
                // 唤醒顾客线程
                coffee.notify();
            }
        }
    }
}
